<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\system\model\SchoolModel;
use app\user\model\UserModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Log;

/**
 * Class UserController
 * @package app\admin\controller
 * @adminMenuRoot(
 *     'name'   => '管理组',
 *     'action' => 'default',
 *     'parent' => 'user/AdminIndex/default',
 *     'display'=> true,
 *     'order'  => 10000,
 *     'icon'   => '',
 *     'remark' => '管理组'
 * )
 */
class UserController extends AdminBaseController
{

    /**
     * 管理员列表
     * @adminMenu(
     *     'name'   => '管理员',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $usersItem = [];//管理员
        $user_mdl = new UserModel();
        $where = ["user_type" => 1];
        /**搜索条件**/
        $user_login = $this->request->param('user_login');
        $user_email = trim($this->request->param('user_email'));

        if ($user_login) {
            $where['user_login'] = ['like', "%$user_login%"];
        }

        if ($user_email) {
            $where['user_email'] = ['like', "%$user_email%"];;
        }
        $users = Db::name('user')->alias('u')
            ->field('u.*')
            ->where($where)
            ->order("id DESC")
            ->paginate(10);
        //获取用户所属的学校
        if(count($users->items()) > 0){
            $usersItem = $users->items();
            foreach ($usersItem as $k=>$v){
                $schools = $user_mdl->getSchoolByUid($v['id'],$v['shop_id']);
                if(!empty($schools)){
                    $usersItem[$k]['school'] = $schools;
                }else{
                    $usersItem[$k]['school'] = [];
                }
            }
        }

        $rolesSrc = Db::name('role')->select();
        $roles    = [];
        foreach ($rolesSrc as $r) {
            $roleId           = $r['id'];
            $roles["$roleId"] = $r;
        }

        $this->assign("page", $users->render());
        $this->assign("roles", $roles);
        $this->assign("users", $usersItem);
        return $this->fetch();
    }


    /**
     * 管理员添加
     * @adminMenu(
     *     'name'   => '管理员添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员添加',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        //学校
        $school_mdl = new SchoolModel();
        $schools = $school_mdl->getAllSchool($this->admin_shop_id);
        //角色
        $roles = Db::name('role')->where(['status' => 1])->order("id DESC")->select();

        $this->assign("schools", $schools);
        $this->assign("roles", $roles);
        return $this->fetch();
    }

    /**
     * 管理员添加提交
     * @adminMenu(
     *     'name'   => '管理员添加提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员添加提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        import('ChinesePinyin.ChinesePinyin', EXTEND_PATH);

        if ($this->request->isPost()) {
            if (!empty($_POST['role_id']) && is_array($_POST['role_id'])) {
                $role_ids = $_POST['role_id'];
                unset($_POST['role_id']);
                $result = $this->validate($this->request->param(), 'User');
                if ($result !== true) {
                    $this->error($result);
                } else {
                    if(empty(trim($_POST['user_login'])) || empty(trim($_POST['user_pass']))){
                        $this->error('用户名和密码都不能为空');
                    }
                    if(empty(trim($_POST['realname']))){
                        $this->error('真实姓名不能为空');
                    }
                    if(empty(trim($_POST['user_email']))){
                        $this->error('邮箱不能为空');
                    }

                    //验证用户名是否已存在
                    $condition = [
                        'shop_id' => $this->admin_shop_id,
                        'user_type' => 1,//用户类型(1后台管理员,2前台用户)
                        'user_login' => trim($_POST['user_login']),
                    ];
                    $user_total = Db::name('user')->where($condition)->count();
                    if($user_total > 0){
                        $this->error('该用户名已存在');
                    }

                    //汉子转换为拼音
                    $realname = trim($_POST['realname']);
                    $pinyin_mdl = new \ChinesePinyin();
                    $user_pinyin = $pinyin_mdl->TransformWithoutTone($realname,'',false);
                    $user_short_pinyin = $pinyin_mdl->TransformUcwords($realname);

                    $_POST['user_pass'] = cmf_password($_POST['user_pass']);
                    //用户所属学校
                    if(empty($_POST['school_id'])){
                        $this->error('请选择学校');
                    }
                    $school_id = $_POST['school_id'];
                    unset($_POST['school_id']);

                    $user_data['user_login'] = trim($_POST['user_login']);
                    $user_data['realname'] = $realname;
                    $user_data['pinyin'] = $user_pinyin;
                    $user_data['short_pinyin'] = $user_short_pinyin;
                    $user_data['user_pass'] = $_POST['user_pass'];
                    $user_data['user_email'] = trim($_POST['user_email']);
                    $user_data['shop_id'] = 1;
                    $user_data['create_time'] = time();

                    $id = DB::name('user')->insertGetId($user_data);
                    if ($id !== false) {
                        //保存所属学校
                        $condition = [
                            'shop_id' => $user_data['shop_id'],
                            'uid' => $id,
                        ];
                        //删除原有的学校
                        Db::name('user_school')->where($condition)->delete();
                        foreach ($school_id as $k=>$v){
                            //新建用户校区
                            $condition['school_id'] = $v;
                            Db::name('user_school')->insert($condition);
                        }

                        //保存用户角色
                        foreach ($role_ids as $role_id) {
                            if (cmf_get_current_admin_id() != 1 && $role_id == 1) {
                                $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                            }
                            Db::name('RoleUser')->insert(["role_id" => $role_id, "user_id" => $id]);
                        }
                        $this->success("添加成功！", url("user/index"));
                    } else {
                        $this->error("添加失败！");
                    }
                }
            } else {
                $this->error("请为此用户指定角色！");
            }

        }
    }

    /**
     * 管理员编辑
     * @adminMenu(
     *     'name'   => '管理员编辑',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员编辑',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id    = $this->request->param('id', 0, 'intval');
        //用户角色
        $roles = DB::name('role')->where(['status' => 1])->order("id DESC")->select();
        $role_ids = DB::name('RoleUser')->where(["user_id" => $id])->column("role_id");
        //编辑用户
        $user = DB::name('user')->where(["id" => $id])->find();
        //获取编辑用户所属学校
        $user_mdl = new UserModel();
        $schools = $user_mdl->getSchoolByUid($user['id'],$user['shop_id']);
        if(!empty($schools)){
            $usersItem = array_column($schools,'school_id');
        }else{
            $usersItem = [];
        }
        //学校
        $school_mdl = new SchoolModel();
        $schools = $school_mdl->getAllSchool($this->admin_shop_id);

        $this->assign($user);
        $this->assign("schools", $schools);
        $this->assign("user_school", $usersItem);
        $this->assign("roles", $roles);
        $this->assign("role_ids", $role_ids);

        return $this->fetch();
    }

    /**
     * 管理员编辑提交
     * @adminMenu(
     *     'name'   => '管理员编辑提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员编辑提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        import('ChinesePinyin.ChinesePinyin', EXTEND_PATH);
        if ($this->request->isPost()) {
            if (!empty($_POST['role_id']) && is_array($_POST['role_id'])) {
                if (empty($_POST['user_pass'])) {
                    unset($_POST['user_pass']);
                } else {
                    $_POST['user_pass'] = cmf_password($_POST['user_pass']);
                }
                $role_ids = $this->request->param('role_id/a');
                unset($_POST['role_id']);
                $res = $this->validate($this->request->param(), 'User.edit');

                if ($res !== true) {
                    // 验证失败 输出错误信息
                    $this->error($res);
                } else {
                    if(empty(trim($_POST['user_login']))){
                        $this->error('用户名和密码都不能为空');
                    }
                    if(empty(trim($_POST['realname']))){
                        $this->error('真实姓名不能为空');
                    }
                    if(empty(trim($_POST['user_email']))){
                        $this->error('邮箱不能为空');
                    }

                    if(empty($_POST['school_id'])){
                        $this->error('请选择学校');
                    }
                    $school_id = $_POST['school_id'];
                    unset($_POST['school_id']);

                    //获取编辑的用户
                    $uid = $this->request->param('id', 0, 'intval');
                    $user = Db::name('user')->find($uid);
                    if(count($user) <= 0){
                        $this->error("此用户不存在");
                    }

                    //修改了用户名
                    if($user['user_login'] != trim($_POST['user_login'])){
                        //验证用户名是否已存在
                        $condition = [
                            'shop_id' => $this->admin_shop_id,
                            'user_type' => 1,//用户类型(1后台管理员,2前台用户)
                            'user_login' => trim($_POST['user_login']),
                        ];
                        $user_total = Db::name('user')->where($condition)->count();
                        if($user_total > 0){
                            $this->error('该用户名已存在');
                        }else{
                            //汉子转换为拼音
                            $_POST['user_login'] = trim($_POST['user_login']);
                        }
                    }

                    //保存真实姓名
                    $_POST['realname'] = trim($_POST['realname']);
                    $pinyin_mdl = new \ChinesePinyin();
                    $_POST['pinyin'] = $pinyin_mdl->TransformWithoutTone($_POST['realname'],'',false);
                    $_POST['short_pinyin'] = $pinyin_mdl->TransformUcwords($_POST['realname']);

                    //保存用户信息
                    $result = DB::name('user')->where('id','=',$uid)->update($_POST);
                    if ($result !== false) {
                        //保存所属学校
                        $condition = [
                            'shop_id' => $user['shop_id'],
                            'uid' => $user['id'],
                        ];
                        //删除原有的学校
                        Db::name('user_school')->where($condition)->delete();
                        foreach ($school_id as $k=>$v){
                            //新建用户校区
                            $condition['school_id'] = $v;
                            Db::name('user_school')->insert($condition);
                        }

                        //处理用户角色
                        DB::name("RoleUser")->where(["user_id" => $uid])->delete();
                        foreach ($role_ids as $role_id) {
                            if (cmf_get_current_admin_id() != 1 && $role_id == 1) {
                                $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                            }
                            DB::name("RoleUser")->insert(["role_id" => $role_id, "user_id" => $uid]);
                        }
                        $this->success("保存成功！",'User/index');
                    } else {
                        $this->error("保存失败！");
                    }
                }
            } else {
                $this->error("请为此用户指定角色！");
            }
        }else{
            $this->error("请求错误！");
        }
    }

    /**
     * 管理员个人信息修改
     * @adminMenu(
     *     'name'   => '个人信息',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员个人信息修改',
     *     'param'  => ''
     * )
     */
    public function userInfo()
    {
        $id   = cmf_get_current_admin_id();
        $user = Db::name('user')->where(["id" => $id])->find();
        $this->assign($user);
        return $this->fetch();
    }

    /**
     * 管理员个人信息修改提交
     * @adminMenu(
     *     'name'   => '管理员个人信息修改提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员个人信息修改提交',
     *     'param'  => ''
     * )
     */
    public function userInfoPost()
    {
        if ($this->request->isPost()) {

            $data             = $this->request->post();
            $data['birthday'] = strtotime($data['birthday']);
            $data['id']       = cmf_get_current_admin_id();
            $create_result    = Db::name('user')->update($data);;
            if ($create_result !== false) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    /**
     * 管理员删除
     * @adminMenu(
     *     'name'   => '管理员删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id == 1) {
            $this->error("最高管理员不能删除！");
        }

        if (Db::name('user')->delete($id) !== false) {
            Db::name("RoleUser")->where(["user_id" => $id])->delete();
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    /**
     * 停用管理员
     * @adminMenu(
     *     'name'   => '停用管理员',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '停用管理员',
     *     'param'  => ''
     * )
     */
    public function ban()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!empty($id)) {
            $result = Db::name('user')->where(["id" => $id, "user_type" => 1])->setField('user_status', '0');
            if ($result !== false) {
                $this->success("管理员停用成功！", url("user/index"));
            } else {
                $this->error('管理员停用失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     * 启用管理员
     * @adminMenu(
     *     'name'   => '启用管理员',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '启用管理员',
     *     'param'  => ''
     * )
     */
    public function cancelBan()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!empty($id)) {
            $result = Db::name('user')->where(["id" => $id, "user_type" => 1])->setField('user_status', '1');
            if ($result !== false) {
                $this->success("管理员启用成功！", url("user/index"));
            } else {
                $this->error('管理员启用失败！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }
}